package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.statistics;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.net.URLEncoder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.InvoiceStatisticsBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.bo.PoundQueryForAdjustPriceBo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.statistics.PoundQueryBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CCompanys;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CIcCardsInfo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CProductsInfo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysRole;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.InvoiceStatisticsExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PoundQueryExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.ProductWeightMoneyNumExportExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICIcCardsInfoService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICProductsInfoService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ICWeightSheetsService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetCWeightSheetsVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.InvoiceStatisticsVo;
import com.xiaoxu.intranetweb.util.StringUtils;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 磅单查询控制器
 *
 * @author xiaoxu
 * @version 1.0
 * @date 2023/1/5 15:00
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/poundQuery")
public class PoundQueryController {
    @Autowired
    private PoundQueryBu poundQueryBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private ICWeightSheetsService iCWeightSheetsService;
    @Autowired
    private WebFunctionUtil webFunctionUtil;
    @Autowired
    private ICProductsInfoService  iCProductsInfoService;
    @Autowired
    private ICIcCardsInfoService iCIcCardsInfoService;
    /**
     * 磅单查询接口
     *
     * @param page          页码
     * @param pageSize      每页条数
     * @param fullTimeStart 开始时间
     * @param fullTimeEnd   结束时间
     * @param coSupply      供应商
     * @param coSupplyChi   供应商子单位名
     * @param co            客户
     * @param chiCo         客户子单位名
     * @param product       品种
     * @param truckno       车牌号
     * @param operator      操作员
     * @param sheetno       磅单号
     * @param reason        原因
     * @param iccardno      卡号
     * @param isEmpty       是否为空
     * @param request       请求
     * @return com.xiaoxu.intranetweb.util.SzResult
     */
    @GetMapping("/getDayPoundQuery")
    public SzResult getDayPoundQuery(@RequestParam(value = "page", required = false) String page,
                                     @RequestParam(value = "pageSize", required = false) String pageSize,
                                     @RequestParam(value = "fullTimeStart", required = false) String fullTimeStart,
                                     @RequestParam(value = "fullTimeEnd", required = false) String fullTimeEnd,
                                     @RequestParam(value = "coSupply", required = false) String coSupply,
                                     @RequestParam(value = "coSupplyChi", required = false) String coSupplyChi,
                                     @RequestParam(value = "co", required = false) String co,
                                     @RequestParam(value = "chiCo", required = false) String chiCo,
                                     @RequestParam(value = "product", required = false) String product,
                                     @RequestParam(value = "truckno", required = false) String truckno,
                                     @RequestParam(value = "operator", required = false) String operator,
                                     @RequestParam(value = "sheetno", required = false) String sheetno,
                                     @RequestParam(value = "reason", required = false) String reason,
                                     @RequestParam(value = "iccardno", required = false) String iccardno,
                                     @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                     @RequestParam(value = "iccardAlias", required = false) String iccardAlias,
                                     HttpServletRequest request) throws Exception {
//        拿到token
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String userId = StpUtil.getLoginIdByToken(token).toString();
        SysRole userRole = userInfoDao.getUserRole(userId);
        //String PlantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
        PoundQueryForAdjustPriceBo poundQueryForAdjustPriceBo = new PoundQueryForAdjustPriceBo();
        poundQueryForAdjustPriceBo.setPage(page);
        poundQueryForAdjustPriceBo.setPageSize(pageSize);
        poundQueryForAdjustPriceBo.setFullTimeStart(fullTimeStart);
        poundQueryForAdjustPriceBo.setFullTimeEnd(fullTimeEnd);
        if (coSupply !=null && coSupply.contains(".")) {
            String[] coSupplyList = coSupply.split("\\.");
            poundQueryForAdjustPriceBo.setCoSupply(coSupplyList[0]);
            poundQueryForAdjustPriceBo.setCoSupplyChi(coSupplyList[1]);
            coSupply = coSupplyList[0];
            coSupplyChi = coSupplyList[1];
        }else {
            poundQueryForAdjustPriceBo.setCoSupply(coSupply);
            poundQueryForAdjustPriceBo.setCoSupplyChi(coSupplyChi);
        }
        if (co !=null && co.contains(".")) {
            String[] coList = co.split("\\.");
            poundQueryForAdjustPriceBo.setCo(coList[0]);
            poundQueryForAdjustPriceBo.setChiCo(coList[1]);
            chiCo = coList[1];
            co = coList[0];
        }else {
            poundQueryForAdjustPriceBo.setCo(co);
            poundQueryForAdjustPriceBo.setChiCo(chiCo);
        }
        List<String> product1 = new ArrayList<>();
        if (product != null && !product.equals("")  ) {
            if ( product.contains(",")) {
                product1 = Stream.of(product.split(",")).collect(Collectors.toList());
            }else{
                product1.add(product);
            }
        }
        poundQueryForAdjustPriceBo.setTruckno(truckno);
        poundQueryForAdjustPriceBo.setOperator(operator);
        poundQueryForAdjustPriceBo.setSheetno(sheetno);
        poundQueryForAdjustPriceBo.setReason(reason);
        poundQueryForAdjustPriceBo.setIccardno(Collections.singletonList(iccardno));

        if (iccardAlias !=null && !iccardAlias.equals("")) {
            QueryWrapper<CIcCardsInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CARDINF_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            queryWrapper.eq("CARDINF_ALIAS", iccardAlias);
            List<CIcCardsInfo> cIcCardsInfos = iCIcCardsInfoService.list(queryWrapper);
            if (cIcCardsInfos.size()>0) {
                List<String> list = new ArrayList<>();
                for (CIcCardsInfo cIcCardsInfo : cIcCardsInfos) {
                    list.add(cIcCardsInfo.getCardinfCardno());
                }
                poundQueryForAdjustPriceBo.setIccardno(list);
            }
        }
        poundQueryForAdjustPriceBo.setIsEmpty(isEmpty);

//        首先不是司机
        if (!userRole.getRoleCode().equals("2222")) {
//        如果是单位用户，只能查询自己单位的数据
            if (userRole.getRoleCode().equals("1111")) {
                List<CCompanys> userCo = userInfoDao.getUserCompany(userId);
                String co1 = userCo.get(0).getCpyCo();

                return poundQueryBu.getCWeightSheetsByTime(page, pageSize, token, fullTimeStart, fullTimeEnd, coSupply, coSupplyChi, co1, chiCo, product1, truckno, operator, sheetno, reason, iccardno, iccardAlias,isEmpty,plantId);
            }
            //        剩下的都是管理员级别用户
            else {
                return poundQueryBu.getCWeightSheetsByTime(page, pageSize, token, fullTimeStart, fullTimeEnd, coSupply, coSupplyChi, co, chiCo, product1, truckno, operator, sheetno, reason, iccardno,iccardAlias, isEmpty,plantId);
            }
        } else {
            return SzResult.Error("司机用户没有权限查询");
        }
    }

    @GetMapping("/getWeightSheets")
    public SzResult getWeightSheets( @RequestParam(value = "fullTimeStart", required = false) String fullTimeStart,
                                     @RequestParam(value = "fullTimeEnd", required = false) String fullTimeEnd,
                                     @RequestParam(value = "coSupply", required = false) String coSupply,
                                     @RequestParam(value = "co", required = false) String co,
                                     @RequestParam(value = "product", required = false) String product,
                                     @RequestParam(value = "truckno", required = false) String truckno,
                                     @RequestParam(value = "operator", required = false) String operator,
                                     @RequestParam(value = "sheetno", required = false) String sheetno,
                                     @RequestParam(value = "reason", required = false) String reason,
                                     @RequestParam(value = "iccardno", required = false) String iccardno,
                                     @RequestParam(value = "isEmpty", required = false) Integer isEmpty,
                                     HttpServletRequest request) throws Exception {
//        拿到token
        String[] saleCo = coSupply.split("\\.");
        String[] buyCo = co.split("\\.");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return poundQueryBu.getWeightSheets(token, fullTimeStart, fullTimeEnd, saleCo[0], saleCo[1], buyCo[0], buyCo[1], product, truckno, operator, sheetno, reason, iccardno, isEmpty,plantId);
    }

    @PostMapping ("/getWeightSheetsExcel")
    public void getWeightSheetsExcel(@RequestBody JSONObject jsonObject, HttpServletRequest request,HttpServletResponse response) throws Exception {
        String fullTimeStart = jsonObject.getString("fullTimeStart");
        String fullTimeEnd = jsonObject.getString("fullTimeEnd");
        String coSupply = jsonObject.getString("coSupply");
        String coSupplyChi = jsonObject.getString("coSupplyChi");
        String co = jsonObject.getString("co");
        String chiCo = jsonObject.getString("chiCo");
        String product = jsonObject.getString("product");
        String truckno = jsonObject.getString("truckno");
        String operator = jsonObject.getString("operator");
        String sheetno = jsonObject.getString("sheetno");
        String reason = jsonObject.getString("reason");
        String iccardno = jsonObject.getString("iccardno");
        Integer isEmpty = jsonObject.getInteger("isEmpty");
//       String iccardAlias
        String iccardAlias = jsonObject.getString("iccardAlias");
//        拿到token
        if (coSupply !=null && co !=null && coSupply.contains(".") && co.contains(".")){
        String[] saleCo = coSupply.split("\\.");
        String[] buyCo = co.split("\\.");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        poundQueryBu.getWeightSheetsExcel(token, fullTimeStart, fullTimeEnd, saleCo[0], saleCo[1], buyCo[0], buyCo[1], product, truckno, operator, sheetno, reason, iccardno,iccardAlias, isEmpty,plantId,response);
        }else{
            String token = request.getHeader("Authorization");
            String plantId = request.getHeader("Plant-Id");
            poundQueryBu.getWeightSheetsExcel(token, fullTimeStart, fullTimeEnd, coSupply, coSupplyChi, co, chiCo, product, truckno, operator, sheetno, reason, iccardno,iccardAlias, isEmpty,plantId,response);
        }
    }
//    @ExcelProperty(value = "装载点")
//    private String weishtAshgateName;
    /**
     * 导出excel
     *
     * @param jsonParam 传入的参数 filename 文件名  fields 实体类  ids 数据  isHeader 是否有表头
     * @param response  响应
     * @param request   请求
     * @return void 无返回值 IO流
     * @throws IOException          IO异常
     * @throws ExecutionException   异常
     * @throws InterruptedException 异常
     */
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        if (!userInfoDao.getUserPermissionWeb(StpUtil.getLoginIdByToken(token).toString()).containsKey("poundQuery_exportExcel")) {
            response.sendError(403, "您没有导出磅单查询excel的权限");
        }
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
//       String fullTimeStart, String fullTimeEnd,
//                                           String coSupply, String coSupplyChi, String co, String chiCo, List<String> product, String truckno, String operator, String sheetno, String reason, String iccardno, Integer isEmpty
        String fullTimeStart = "", fullTimeEnd = "", coSupply = "", coSupplyChi = "", co = "", chiCo = "", truckno = "", operator = "", sheetno = "", reason = "", iccardno = "",iccardAlias="";
        Integer isEmpty = null;
      String product = "";
        List<String> product1 = new ArrayList<>();
        if (form != null) {
            if (form.get("fullTimeStart") != null) {
                fullTimeStart = (String) form.get("fullTimeStart");
            }
            if (form.get("fullTimeEnd") != null) {
                fullTimeEnd = (String) form.get("fullTimeEnd");
            }
            if (form.get("coSupply") != null) {
                coSupply = (String) form.get("coSupply");
            }
            if (form.get("coSupplyChi") != null) {
                coSupplyChi = (String) form.get("coSupplyChi");
            }
            if (form.get("co") != null) {
                co = (String) form.get("co");
            }
            if (form.get("chiCo") != null) {
                chiCo = (String) form.get("chiCo");
            }
            if (form.get("truckno") != null) {
                truckno = (String) form.get("truckno");
            }
            if (form.get("operator") != null) {
                operator = (String) form.get("operator");
            }
            if (form.get("sheetno") != null) {
                sheetno = (String) form.get("sheetno");
            }
            if (form.get("reason") != null) {
                reason = (String) form.get("reason");
            }
            if (form.get("iccardno") != null) {
                iccardno = (String) form.get("iccardno");
            }
            if (form.get("iccardAlias") != null && !form.get("iccardAlias").equals("null")) {
                iccardAlias = (String) form.get("iccardAlias");
            }
            if (form.get("isEmpty") != null) {
                isEmpty = Integer.parseInt((String) form.get("isEmpty"));
            }

            if (form.get("product") != null) {
                // 获取 JSONArray
                JSONArray productArray = (JSONArray) form.get("product");

                // 手动转换为 List<String>

                for (int i = 0; i < productArray.size(); i++) {
                    product1.add(productArray.getString(i));
                }
//                QueryWrapper<CProductsInfo>  cProductsInfoQueryWrapper = new QueryWrapper<>();
//                cProductsInfoQueryWrapper.eq("PDTINF_ID", form.get("product"));
//                cProductsInfoQueryWrapper.ge("DATA_FROM",plantId);
//                cProductsInfoQueryWrapper.eq("PDTINF_DELETED",0);
//                CProductsInfo cProductsInfo = iCProductsInfoService.getOne(cProductsInfoQueryWrapper);
            }
        }
//exportExcel为异步方法，需要在调用处加上@Async注解
       List<PoundQueryExcelEn> poundQueryExcelBos1 = poundQueryBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, fullTimeStart, fullTimeEnd, coSupply, coSupplyChi, co, chiCo, product1, truckno, operator, sheetno, reason, iccardno,iccardAlias, isEmpty,plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
//       拿到List<PoundQueryExcelBo> 之后，进行导出
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), PoundQueryExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet(sheetName)
                .doWrite(poundQueryExcelBos1);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
//   public SzResult exportInvoiceStatistics(String coId, String supplyCoId,  String pdtId,String startTime,String endTime) throws Exception {
    @GetMapping("/invoiceStatistics")
    public SzResult invoiceStatistics(
            @RequestParam(value = "coId", required = false) String coId,
            @RequestParam(value = "supplyCoId", required = false) String supplyCoId,
            @RequestParam(value = "pdtId", required = false) String pdtId,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime
    ) throws Exception {
        List<InvoiceStatisticsVo> invoiceStatisticsVos = poundQueryBu.exportInvoiceStatistics(coId,supplyCoId,pdtId,startTime,endTime);
        return SzResult.success(invoiceStatisticsVos);
    }

    @PostMapping("/exportInvoiceStatistics")
    public void exportInvoiceStatistics(
            @RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request
    ) throws Exception {
        String coId = jsonParam.getString("coId");
        String supplyCoId = jsonParam.getString("supplyCoId");
        String pdtId = jsonParam.getString("pdtId");
        String startTime = jsonParam.getString("startTime");
        String endTime = jsonParam.getString("endTime");
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<InvoiceStatisticsVo> invoiceStatisticsVos =  poundQueryBu.exportInvoiceStatistics(coId,supplyCoId,pdtId,startTime,endTime);
//invoiceStatisticsVos转excel
        List<InvoiceStatisticsExcelEn> invoiceStatisticsExcelEn =  poundQueryBu.exportInvoiceStatisticsExcel(invoiceStatisticsVos);
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("发票统计-"+startTime+"~"+endTime, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), InvoiceStatisticsExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("发票统计").doWrite(invoiceStatisticsExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}


